package com.spider.spiderflowable.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yitter.idgen.YitIdHelper;
import com.spider.spiderflowable.business.constant.ApprovalConstant;
import com.spider.spiderflowable.business.entity.dto.ExecApprovalFlowInstParam;
import com.spider.spiderflowable.business.entity.model.FlowApprovalHistory;
import com.spider.spiderflowable.business.entity.model.FlowApprovalRequest;
import com.spider.spiderflowable.business.entity.param.ApprovalFlowCallbackParam;
import com.spider.spiderflowable.business.entity.param.ApprovalParam;
import com.spider.spiderflowable.business.entity.param.ApprovalQueryParam;
import com.spider.spiderflowable.business.entity.param.ApprovalRequestSubmitParam;
import com.spider.spiderflowable.business.entity.param.CompleteProcessDto;
import com.spider.spiderflowable.business.entity.vo.FlowApprovalRequestVo;
import com.spider.spiderflowable.business.entity.vo.ProcessInstResultVo;
import com.spider.spiderflowable.business.enums.ApprovalStatusEnum;
import com.spider.spiderflowable.business.enums.OperationTypeEnum;
import com.spider.spiderflowable.business.enums.RequestTypeEnum;
import com.spider.spiderflowable.business.mapper.FlowApprovalHistoryMapper;
import com.spider.spiderflowable.business.mapper.FlowApprovalRequestMapper;
import com.spider.spiderflowable.business.service.ApprovalRequestService;
import com.spider.spiderflowable.business.service.INumberGenService;
import com.spider.spiderflowable.common.CurrentUserInfo;
import com.spider.spiderflowable.common.MybatisBeanUtil;
import com.spider.spiderflowable.core.entity.dto.InstanceResultInfoData;
import com.spider.spiderflowable.core.entity.vo.FlowableTaskVO;
import com.spider.spiderflowable.core.service.SpiderProcessInstanceService;
import com.spider.spiderflowable.core.service.SpiderTaskService;
import com.spider.spiderflowable.exception.BusinessException;
import com.spider.spiderflowable.utils.BeanUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.identitylink.api.IdentityLink;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

/**
 * @author xiong.bo
 * @version 1.0
 * @date 2025/4/20 3:10 下午
 */

@Slf4j
@Service
public class ApprovalRequestServiceImpl implements ApprovalRequestService {


  @Autowired
  private SpiderTaskService spiderTaskService;
  @Autowired
  private SpiderProcessInstanceService spiderProcessInstanceService;

  @Autowired
  private INumberGenService numberGenService;



  @Autowired
  private FlowApprovalRequestMapper approvalRequestMapper;
  @Autowired
  private FlowApprovalHistoryMapper approvalHistoryMapper;
//  @Autowired
//  private FlowRoleConfigMapper roleConfigMapper;

  // 流程定义key,每一种审批类型固定,非正常关单申请的流程定义KEY
  public static final String ORDER_ABNORMAL_CLOSE_APPROVAL_PROCESS_KEY = "process_order_abnormal_close_approval";


  @Override
  public FlowApprovalRequest submitApply(ApprovalRequestSubmitParam param) {

    /**
     * 根据业务Id查询是否已生成过申请记录
     * 1，如果未生成, 则启动流程实例，并生成申请记录,并再次调用执行流程走到待审批节点
     * 2，如果已生成，则直接调用执行流程走到待审批节点
     */
    String businessId = param.getBusinessId();
    String requestType = param.getRequestType();
    LambdaQueryWrapper<FlowApprovalRequest> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(FlowApprovalRequest::getBusinessId, businessId);
    queryWrapper.eq(FlowApprovalRequest::getRequestType, requestType);
    queryWrapper.ne(FlowApprovalRequest::getApprovalStatus, ApprovalStatusEnum.EXPIRED.getCode());
    List<FlowApprovalRequest> requestList = approvalRequestMapper.selectList(queryWrapper);
    FlowApprovalRequest approvalRequest = null;
    if (ObjectUtil.isEmpty(requestList)) {
      // 启动流程实例,生成申请记录
      approvalRequest = createApprovalRequest(param);
    } else {
      approvalRequest = requestList.get(0);
      editSetRequest(param, approvalRequest);
    }

    // 如果已存在的申请处在待审批中,给出提示
    if (ApprovalStatusEnum.PENDING.getCode().equals(approvalRequest.getApprovalStatus())) {
      throw new BusinessException("该工单处于非正常关单审批中,请及时联系审批人");
    }
    if (ApprovalStatusEnum.APPROVED.getCode().equals(approvalRequest.getApprovalStatus())) {
      String messageText = CharSequenceUtil.format("该审批已通过,不能再次提交.申请类型:{},业务id:{}", requestType, businessId);
      throw new BusinessException(messageText);
    }

    // 执行流程实例,从待提交节点流转到待审批节点
    Map<String, Object> parameters = new HashMap<>();
    // 记录到流程实例变量中,后续搜索需要用到
    parameters.put(ApprovalConstant.VAR_PREFIX + ApprovalConstant.VAR_TITLE, approvalRequest.getTitle());
    parameters.put(ApprovalConstant.VAR_PREFIX + ApprovalConstant.VAR_REQUEST_NO, approvalRequest.getRequestNo());

    ExecApprovalFlowInstParam instParam = new ExecApprovalFlowInstParam();
    instParam.setWorkFlowTaskId(approvalRequest.getTaskInstanceId());
    instParam.setAssigneeApprover(param.getAssigneeApprover());
    instParam.setAssigneeApproverName(param.getAssigneeApproverName());
    instParam.setParameters(parameters);

    CompleteProcessDto completeProcessDto = completeApprovalRequest(approvalRequest, instParam);
    OperationTypeEnum operationTypeEnum = OperationTypeEnum.SUBMIT_REQUEST;
    if (ObjectUtil.isNotEmpty(requestList)) {
      operationTypeEnum = OperationTypeEnum.RE_SUBMIT_REQUEST;
    }
    CurrentUserInfo userInfo = new CurrentUserInfo();
    userInfo.setUserId(1L);
    userInfo.setUserName("admin");
    userInfo.setUserId(param.getApplicationId());
    userInfo.setUserName(param.getApplicationName());
    saveApprovalHistory(approvalRequest, operationTypeEnum, null, userInfo);

    return approvalRequest;
  }

  private static void editSetRequest(ApprovalRequestSubmitParam param, FlowApprovalRequest approvalRequest) {
    String title = param.getApplicationName() + ApprovalConstant.APPROVAL_CONSTANT + param.getRequestTypeName();
    approvalRequest.setTitle(title);
    approvalRequest.setRequestContent(param.getApplicationReason());
    approvalRequest.setApplicantId(param.getApplicationId());
    approvalRequest.setApplicantName(param.getApplicationName());
    approvalRequest.setBusinessId(param.getBusinessId());
    approvalRequest.setBusinessSource(param.getBusinessSource());
    approvalRequest.setBusinessCallbackUrl(param.getBusinessCallbackUrl());
    if (ObjectUtil.isNotEmpty(param.getBusinessInfo())) {
      approvalRequest.setBusinessInfo(param.getBusinessInfo());
    }
    approvalRequest.setCurrentApproverId(param.getAssigneeApprover());
    approvalRequest.setCurrentApproverName(param.getAssigneeApproverName());
  }

  @Override
  public FlowApprovalRequest approveRequest(ApprovalParam param) {
    log.info("审批通过接口入参:param:{}", JSON.toJSONString(param));

    FlowApprovalRequest approvalRequest = selectApprovalById(param.getId());
//    CurrentUserInfo userInfo = UserHelper.getUser();
    // todo 待完善
    CurrentUserInfo userInfo = new CurrentUserInfo();
    userInfo.setUserId(1L);
    userInfo.setUserName("admin");

    // 任务签收
    spiderTaskService.claim(approvalRequest.getTaskInstanceId(), String.valueOf(userInfo.getUserId()));

    // 执行流程实例,进行审批操作
    Map<String, Object> parameters = new HashMap<>();
    parameters.put(ApprovalConstant.FLOWABLE_TASK_OUTCOME, ApprovalConstant.FLOWABLE_TASK_OUTCOME_APPROVE);
    ExecApprovalFlowInstParam instParam = new ExecApprovalFlowInstParam();
    instParam.setWorkFlowTaskId(approvalRequest.getTaskInstanceId());
    instParam.setParameters(parameters);
    CompleteProcessDto completeProcessDto = completeApprovalRequest(approvalRequest, instParam);

    saveApprovalHistory(approvalRequest, OperationTypeEnum.APPROVE_REQUEST, param.getApprovalComment(), userInfo);

    // 如果区域运营经理下没有审批人,则自动审核通过
    boolean autoNext = completeProcessDto.isAutoNext();
    if (autoNext) {
      // 执行流程实例,进行审批操作
      parameters.put(ApprovalConstant.FLOWABLE_TASK_OUTCOME, ApprovalConstant.FLOWABLE_TASK_OUTCOME_APPROVE);
      instParam.setParameters(parameters);
      instParam.setWorkFlowTaskId(approvalRequest.getTaskInstanceId());
      completeApprovalRequest(approvalRequest, instParam);
    }

    // 回调业务系统,传递审批状态
    approvalCallback(approvalRequest);

    return approvalRequest;
  }

  @Override
  public FlowApprovalRequest rejectRequest(ApprovalParam param) {
    log.info("审批驳回接口入参:param:{}", JSON.toJSONString(param));

    FlowApprovalRequest approvalRequest = selectApprovalById(param.getId());
//    CurrentUserInfo userInfo = UserHelper.getUser();
    // todo 待完善
    CurrentUserInfo userInfo = new CurrentUserInfo();
    userInfo.setUserId(1L);
    userInfo.setUserName("admin");

    // 任务签收
    spiderTaskService.claim(approvalRequest.getTaskInstanceId(), String.valueOf(userInfo.getUserId()));

    // 执行流程实例,进行审批操作
    Map<String, Object> parameters = new HashMap<>();
    parameters.put(ApprovalConstant.FLOWABLE_TASK_OUTCOME, ApprovalConstant.FLOWABLE_TASK_OUTCOME_REJECT);
    ExecApprovalFlowInstParam instParam = new ExecApprovalFlowInstParam();
    instParam.setWorkFlowTaskId(approvalRequest.getTaskInstanceId());
    instParam.setParameters(parameters);
    completeApprovalRequest(approvalRequest, instParam);

    saveApprovalHistory(approvalRequest, OperationTypeEnum.REJECT_REQUEST, param.getApprovalComment(), userInfo);

    // 回调业务系统,传递审批状态
    approvalCallback(approvalRequest);

    return approvalRequest;
  }

  @Override
  public IPage<FlowApprovalRequestVo> selectPage(ApprovalQueryParam param) {

    IPage<FlowApprovalRequestVo> requestVoIPage = new Page<>();
    Page<FlowApprovalRequest> pageModel = new Page<>(param.getPage(), param.getLimit());
    if (ObjectUtil.isEmpty(param.getDoneType()) || (!ApprovalConstant.DONE_TYPE_TO_DO.equals(param.getDoneType())
        && !ApprovalConstant.DONE_TYPE_DONE.equals(param.getDoneType()))) {
      throw new BusinessException("doneType参数为空或者不正确");
    }

    // todo fix
//    CurrentUserInfo userInfo = UserHelper.getUser();
    CurrentUserInfo userInfo = new CurrentUserInfo();
    userInfo.setUserId(1L);
    userInfo.setUserName("admin");
    String staffId = String.valueOf(userInfo.getUserId());

    Page<FlowableTaskVO> flowableTaskVOPage;
    if (ApprovalConstant.DONE_TYPE_TO_DO.equals(param.getDoneType())) {
      flowableTaskVOPage = spiderTaskService.queryTodoTask(staffId, param);
    } else {
      flowableTaskVOPage = spiderTaskService.queryDoneHisTask(staffId, param);
    }
    if (ObjectUtil.isEmpty(flowableTaskVOPage)) {
      return requestVoIPage;
    }
    List<FlowableTaskVO> records = flowableTaskVOPage.getRecords();

    if (ObjectUtil.isEmpty(records)) {
      return requestVoIPage;
    }

    List<String> processInstIdList = records.stream().map(FlowableTaskVO::getProcessInstanceId).collect(
        Collectors.toList());

    LambdaQueryWrapper<FlowApprovalRequest> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.in(FlowApprovalRequest::getProcessInstanceId, processInstIdList);
    queryWrapper.orderByDesc(FlowApprovalRequest::getCreateTime);
    IPage<FlowApprovalRequest> approvalRequestIPage = approvalRequestMapper.selectPage(
        pageModel, queryWrapper);

    requestVoIPage = MybatisBeanUtil.convertPage(approvalRequestIPage, FlowApprovalRequestVo.class);
    return requestVoIPage;
  }

  @Override
  public FlowApprovalRequestVo findById(Long id) {
    FlowApprovalRequestVo requestVo = new FlowApprovalRequestVo();
    FlowApprovalRequest flowApprovalRequest = approvalRequestMapper.selectById(id);
    BeanUtil.copyProperties(flowApprovalRequest, requestVo);

    // todo
//    CurrentUserInfo userInfo = UserHelper.getUser();
    CurrentUserInfo userInfo = new CurrentUserInfo();
    if (userInfo != null && ApprovalStatusEnum.PENDING.getCode()
        .equals(flowApprovalRequest.getApprovalStatus())) {
      // 查询是否有审批权限
      String userId = String.valueOf(userInfo.getUserId());
      List<IdentityLink> identityLinksForTask = spiderTaskService.getIdentityLinksForTask(
          flowApprovalRequest.getTaskInstanceId());
      if (ObjectUtil.isNotEmpty(identityLinksForTask)) {
        for (IdentityLink identityLink : identityLinksForTask) {
          if (userId.equals(identityLink.getUserId())) {
            requestVo.setDisplayApproveStatus(true);
            break;
          }
        }
      }
    }
    requestVo.setRequestTypeName(RequestTypeEnum.getDescByCode(requestVo.getRequestType()));
    return requestVo;
  }

  @Override
  public List<FlowApprovalHistory> selectHistoryById(Long id) {
    LambdaQueryWrapper<FlowApprovalHistory> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(FlowApprovalHistory::getRequestId, id);
    queryWrapper.orderByDesc(FlowApprovalHistory::getCreateTime);
    return approvalHistoryMapper.selectList(queryWrapper);
  }

//  @Override
//  public List<FlowRoleConfig> getRoleByType(ApprovalRequestParam param) {
//    // 此接口返回给外部的是流程第一个节点的角色编码
//    if (RequestTypeEnum.REQUEST_ABNORMAL_CLOSE.getCode().equals(param.getRequestType())) {
//      param.setRoleCode(RoleEnum.PROJECT_MANAGER.getCode());
//    }
//
//    LambdaQueryWrapper<FlowRoleConfig> queryWrapper = new LambdaQueryWrapper<>();
//    queryWrapper.eq(FlowRoleConfig::getRoleCode, param.getRoleCode());
//    return roleConfigMapper.selectList(queryWrapper);
//  }

  @Override
  public boolean expiredRequest(String processInstanceId) {
    if (ObjectUtil.isEmpty(processInstanceId)) {
      return false;
    }
    LambdaQueryWrapper<FlowApprovalRequest> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(FlowApprovalRequest::getProcessInstanceId, processInstanceId);
    List<FlowApprovalRequest> approvalRequests = approvalRequestMapper.selectList(queryWrapper);
    if (ObjectUtil.isNotEmpty(approvalRequests)) {
      FlowApprovalRequest request = approvalRequests.get(0);
      request.setApprovalStatus(ApprovalStatusEnum.EXPIRED.getCode());
      approvalRequestMapper.updateById(request);
      log.info("更新审批状态为已过期,审批编码:{}", request.getRequestNo());
    }
    return true;
  }

  // 根据业务id查询申请审批记录
  private FlowApprovalRequest selectApprovalById(Long approvalId) {

    FlowApprovalRequest approvalRequest = approvalRequestMapper.selectById(approvalId);
    if (ObjectUtil.isEmpty(approvalRequest)) {
      log.error("不存在此非正常关单审批,数据ID:{}", approvalId);
      throw new BusinessException("不存在此非正常关单审批");
    }
    if (ApprovalStatusEnum.APPROVED.getCode().equals(approvalRequest.getApprovalStatus())) {
      log.error("流程已审批完成,请勿重复审批,数据ID:{}", approvalId);
      throw new BusinessException("流程已审批完成,请勿重复审批");
    }
    if (!ApprovalStatusEnum.PENDING.getCode().equals(approvalRequest.getApprovalStatus())) {
      log.error("流程非审批中状态,不能审批,数据ID:{}", approvalId);
      throw new BusinessException("流程非审批中状态,不能审批");
    }
    return approvalRequest;
  }


  // 启动流程实例,生成申请记录
  private FlowApprovalRequest createApprovalRequest(ApprovalRequestSubmitParam param) {

    String title = param.getApplicationName() + ApprovalConstant.APPROVAL_CONSTANT + param.getRequestTypeName();
    String requestNo = numberGenService.generateNumberByTime(ApprovalConstant.APPROVAL_REQUEST_ID_PREFIX);

    Long tenantId = param.getTenantId();
    Map<String, Object> parameters = new HashMap<>();
    // 记录到流程实例变量中,后续搜索需要用到
    parameters.put(ApprovalConstant.VAR_PREFIX + ApprovalConstant.VAR_TITLE, title);
    parameters.put(ApprovalConstant.VAR_PREFIX + ApprovalConstant.VAR_REQUEST_NO, requestNo);
    String processDefinitionKey = null;
    if (RequestTypeEnum.REQUEST_ABNORMAL_CLOSE.getCode().equals(param.getRequestType())) {
      processDefinitionKey = ORDER_ABNORMAL_CLOSE_APPROVAL_PROCESS_KEY;
    }
    if (StringUtils.isBlank(processDefinitionKey)) {
      throw new BusinessException("提交失败,没有配置该类型的申请模板");
    }
    // 启动流程实例
    List<FlowableTaskVO> flowableTaskVOList = spiderProcessInstanceService.startProcessInstanceByKeyAndTenantId(
        processDefinitionKey, param.getBusinessId(), parameters, String.valueOf(tenantId));

    if (ObjectUtil.isEmpty(flowableTaskVOList)) {
      throw new BusinessException("提交失败,请联系管理员");
    }

    FlowableTaskVO flowableTaskVO = flowableTaskVOList.get(0);
    log.info("流程实例信息:{}", JSON.toJSONString(flowableTaskVO));

    // 写入非关申请记录
    FlowApprovalRequest acApproval = new FlowApprovalRequest();

    acApproval.setId(YitIdHelper.nextId());
    acApproval.setTenantId(tenantId);
    acApproval.setRequestNo(requestNo);
    acApproval.setRequestType(param.getRequestType());
    // 申请人+申请类型
    acApproval.setTitle(title);
    acApproval.setRequestContent(param.getApplicationReason());
    acApproval.setApplicantId(param.getApplicationId());
    acApproval.setApplicantName(param.getApplicationName());
    acApproval.setApprovalStatus(ApprovalStatusEnum.DRAFT.getCode());
    acApproval.setBusinessId(param.getBusinessId());
    acApproval.setBusinessSource(param.getBusinessSource());
    acApproval.setBusinessCallbackUrl(param.getBusinessCallbackUrl());
    acApproval.setBusinessInfo(param.getBusinessInfo());
    acApproval.setCurrentApproverId(param.getAssigneeApprover());
    acApproval.setCurrentApproverName(param.getAssigneeApproverName());

    acApproval.setProcessInstanceId(flowableTaskVO.getProcessInstanceId());
    acApproval.setTaskInstanceId(flowableTaskVO.getId());
    acApproval.setProcessDefinitionKey(flowableTaskVO.getProcessDefinitionKey());
    acApproval.setTaskDefinitionKey(flowableTaskVO.getTaskDefinitionKey());
    acApproval.setCreateUser(param.getApplicationName());
    approvalRequestMapper.insert(acApproval);
    return acApproval;
  }

  // 执行流程实例
  private CompleteProcessDto completeApprovalRequest(FlowApprovalRequest approvalRequest, ExecApprovalFlowInstParam instParam) {

    CompleteProcessDto completeProcessDto = new CompleteProcessDto();
    ProcessInstResultVo resultVo = spiderTaskService.completeProcessInst(instParam);
    List<InstanceResultInfoData> actives = resultVo.getActives();
    if (resultVo.getProcessIsFinish()) {
      // 审批通过,流程结束
      // todo
      CurrentUserInfo userInfo = new CurrentUserInfo();
      userInfo.setUserId(1L);
      userInfo.setUserName("admin");
      approvalRequest.setApprovalStatus(ApprovalStatusEnum.APPROVED.getCode());
      approvalRequest.setUpdateUser(userInfo.getUserName());
      approvalRequestMapper.updateById(approvalRequest);
      return completeProcessDto;
    }

    if (ObjectUtil.isEmpty(actives)) {
      log.error("流程未结束,但是活动的用户任务为空,数据异常,taskInstanceId:{}", approvalRequest.getTaskInstanceId());
      throw new BusinessException("流程实例已结束,提交失败");
    }
    InstanceResultInfoData instanceData = actives.get(0);
    String category = instanceData.getCategory();

    List<String> userIdList = getTaskAssignees(approvalRequest, instParam, category, completeProcessDto);
    log.info("流程实例分配候选用户,processInstanceId:{},taskInstanceId:{},userId集合:{}",
        approvalRequest.getProcessInstanceId(), approvalRequest.getTaskInstanceId(), JSON.toJSONString(userIdList));
    completeProcessDto.setUserIdList(userIdList);

    // 将用户加入用户任务的候选组中
    spiderTaskService.addTaskCandidateUser(instanceData.getId(), userIdList);

    // 获取到用户任务的业务状态
    // 固定格式,flowable:category="project-manager:项目经理:toBeReviewed"
    String bpmStatus = category;
    if (category != null && category.contains(":")) {
      String[] split = category.split(":");
      if (split.length == 3) {
        bpmStatus = split[2];
      }
    }
    String approvalStatus = ApprovalStatusEnum.PENDING.getCode();
    if (ApprovalStatusEnum.DRAFT.getCode().equals(bpmStatus)) {
      approvalStatus = ApprovalStatusEnum.DRAFT.getCode();
    } else if (ApprovalStatusEnum.PENDING.getCode().equals(bpmStatus)) {
      approvalStatus = ApprovalStatusEnum.PENDING.getCode();
    }
    approvalRequest.setApprovalStatus(approvalStatus);
    approvalRequest.setTaskInstanceId(instanceData.getId());
    approvalRequestMapper.updateById(approvalRequest);
    return completeProcessDto;
  }


  /**
   * 获取任务审批人
   * 当前只支持分配一个人或配置一个角色的方式
   *
   * @param approvalRequest
   * @param instParam
   * @param category
   * @param completeProcessDto
   * @return
   */
  private List<String> getTaskAssignees(FlowApprovalRequest approvalRequest, ExecApprovalFlowInstParam instParam,
      String category, CompleteProcessDto completeProcessDto) {
    List<String> userIdList = new ArrayList<>();

    String roleCode = "";
    String roleName = "";
    // 固定格式,flowable:category="project-manager:项目经理:toBeReviewed"
    if (category != null && category.contains(":")) {
      String[] split = category.split(":");
      if (split.length >= 2) {
        roleCode = split[0];
        roleName = split[1];
      }
    }

    Long assigneeApprover = instParam.getAssigneeApprover();
    if (assigneeApprover != null) {
      userIdList.add(String.valueOf(assigneeApprover));
    } else {
      // 按实际业务获取候选用户
      userIdList.add("1L");
      userIdList.add("2L");
    }
    return userIdList;
  }

  // 保存审批历史记录
  private void saveApprovalHistory(FlowApprovalRequest approvalRequest, OperationTypeEnum operationTypeEnum,
      String comment, CurrentUserInfo userInfo) {
    // 审批历史记录
    FlowApprovalHistory approvalHistory = new FlowApprovalHistory();
    approvalHistory.setRequestId(approvalRequest.getId());
    approvalHistory.setRequestNo(approvalRequest.getRequestNo());
    approvalHistory.setProcessInstanceId(approvalRequest.getProcessInstanceId());
    approvalHistory.setTaskInstanceId(approvalRequest.getTaskInstanceId());

    if (userInfo != null) {
      approvalHistory.setOperatorId(userInfo.getUserId());
      approvalHistory.setOperatorName(userInfo.getUserName());
    }

    approvalHistory.setOperationType(operationTypeEnum.getType());
    String operationTitle = approvalHistory.getOperatorName() + operationTypeEnum.getDesc();
    approvalHistory.setOperationTitle(operationTitle);
    approvalHistory.setOperationComment(comment);
    approvalHistory.setOperationTime(new Date());
    approvalHistory.setCreateUser(null);
    approvalHistoryMapper.insert(approvalHistory);
  }

  // 回调业务系统,传递审批状态
  private void approvalCallback(FlowApprovalRequest approvalRequest) {
    try {
      // 按实际业务处理回调逻辑
      ApprovalFlowCallbackParam callbackParam = new ApprovalFlowCallbackParam();
      callbackParam.setOrderNo(approvalRequest.getBusinessId());
      callbackParam.setApprovalFlowNo(approvalRequest.getRequestNo());
      callbackParam.setApprovalFlowCode(approvalRequest.getApprovalStatus());
      callbackParam.setTenantId(approvalRequest.getTenantId());
      callbackParam.setBusinessCallbackUrl(approvalRequest.getBusinessCallbackUrl());
      String requestUrl = callbackParam.getBusinessCallbackUrl();
      if (ObjectUtil.isEmpty(requestUrl)) {
        log.info("审批状态变更,调用方没有传入回调地址,则没有回调推送");
        return;
      }
      HttpHeaders httpHeaders = new HttpHeaders();
      httpHeaders.set("X-Auth-Token", "Y2FsbGNlbnRlcjphcHByb3ZhbGZsb3c=");
      HttpRequest httpRequest = HttpUtil.createPost(requestUrl);
      httpRequest.body(JSONUtil.toJsonStr(callbackParam));
      httpRequest.header(httpHeaders);
      HttpResponse httpResponse = httpRequest.execute();
      log.info("approvalCallback respBody:{}", httpResponse.body());
    } catch (Exception e) {
      log.error("审批回调失败.", e);
    }
  }



}
